package org.jeecg.modules.kuawcsJs.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.agCarGps.entity.AgCarGps;
import org.jeecg.modules.agCarGps.service.IAgCarGpsService;
import org.jeecg.modules.car.entity.CarInfo;
import org.jeecg.modules.car.service.ICarInfoService;
import org.jeecg.modules.kuawcsJs.entity.AgKuawcsJs;

import org.jeecg.modules.kuawcsJs.entity.FtpUtil;
import org.jeecg.modules.kuawcsJs.mapper.AgKuawcsJsMapper;
import org.jeecg.modules.kuawcsJs.service.IAgKuawcsJsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 跨网传输接收
 * @Author: jeecg-boot
 * @Date:   2020-10-28
 * @Version: V1.0
 */
@Slf4j
@Service
public class AgKuawcsJsServiceImpl extends ServiceImpl<AgKuawcsJsMapper, AgKuawcsJs> implements IAgKuawcsJsService {
    @Autowired
    private IAgKuawcsJsService agKuawcsJsService;

    @Autowired
    private IAgCarGpsService agCarGpsService;

    @Autowired
    private ICarInfoService carInfoService;

    @Value("${kwakcs.savePath}")
    String savePath = "";

    @Value("${kwakcs.guangpnwIp}")
    String guangpnwIp= "";

    @Value("${kwakcs.username}")
    String username= "" ;

    @Value("${kwakcs.password}")
    String password= "";

    @Value("${kwakcs.port}")
    int port;


    /*
    二维码接收
     */

    @Override
    public Result<?> receiveFile(HttpServletRequest request, HttpServletResponse response) {

        log.info("跨网传输二维码接收开始"+ DateUtils.formatDateTime());
        AgKuawcsJs agKuawcsJs = new AgKuawcsJs();
        agKuawcsJs.setJieskssj(new Date());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ObjectMapper mapper = new ObjectMapper();
        String sysName = request.getParameter("sysName");
        String fileName = request.getParameter("fileName");

        Date d = new Date();
        String dateDir = new SimpleDateFormat("yyyy\\MM\\dd\\HH\\mm\\ss").format(d);
        String fileFullPath = savePath + File.separator + sysName + File.separator +dateDir+File.separator + fileName;
        InputStream in = null;
        FileOutputStream fos = null;
        String ret = "";
        try {
            in = request.getInputStream();


            File file = new File(savePath +File.separator + sysName+ File.separator +dateDir);
            if(!file.exists()){
                file.mkdirs();
            }
            fos = new FileOutputStream(fileFullPath);
            ret = fileName;
            int size = 0;
            byte[] buffer = new byte[1024];
            while ((size = in.read(buffer,0,1024)) != -1) {
                fos.write(buffer, 0, size);
            }

            agKuawcsJs.setChuansfs("2");

            agKuawcsJs.setJieswjm(sysName);
            agKuawcsJs.setBaoclj(fileFullPath);
            agKuawcsJs.setDuqsj(new Date());




            //响应信息
            Map<String,Object> responseMap = new HashMap<String,Object>();
            responseMap.put("status", true);
            String jsonResponse = mapper.writeValueAsString(responseMap);
            sendResponse(jsonResponse,response,ret);
            ret = ret+"  "+"接收成功！";


        } catch (IOException e) {
            //响应信息
            Map<String,Object> responseMap = new HashMap <String,Object>();
            responseMap.put("status", false);
            responseMap.put("errorMsg", e.getMessage());
            String jsonResponse = "";
            try {
                jsonResponse = mapper.writeValueAsString(responseMap);
            } catch (JsonProcessingException e1) {
                ret = ret+"  "+"接收失败！";
                log.error("接收失败",e);

            }
            sendResponse(jsonResponse,response,ret);

        } finally{
            close(in, fos,ret);
            //移动文件到摆渡目录
        }

        agKuawcsJs.setJieswcsj(new Date());
        agKuawcsJsService.save(agKuawcsJs);

//同步ag_car_gps数据库
        if (fileName.endsWith("ag_car_gps.json")){

                 syncCarGps(fileName,fileFullPath);
            }

        return null;

    }



    private void syncCarGps(String fileName, String fileFullPath) {
//同步ag_car_gps数据库
//        if (fileName.endsWith("ag_car_gps.json")){
            /*
             * 取出文件内容，填充对象
             */
            try {

                String s = ReadFile(fileFullPath);//获得json文件的内容

                List <AgCarGps> list= JSON.parseObject(s,new TypeReference <List <AgCarGps>>(){});

                for (AgCarGps agCarGps:list
                ) {

                    AgCarGps carGps = agCarGpsService.getOne(new QueryWrapper <AgCarGps>().eq("id", agCarGps.getId()));
                    agCarGps.setChuanswczt("1");

                    CarInfo carInfo = carInfoService.getOne(new QueryWrapper<CarInfo>().eq("imei", agCarGps.getImei()), false);
                if (carInfo != null) {
                    agCarGps.setCheph(carInfo.getId());
                }

                    if (carGps!=null){
                        agCarGpsService.updateById(agCarGps);
                    }else {
                        agCarGpsService.save(agCarGps);
                    }
//                    AgKuawcsJs agKuawcsJs = new AgKuawcsJs();
//                    agKuawcsJs.setJieskssj(new Date());
//                    agKuawcsJs.setChuansfs("2");
//
//                    agKuawcsJs.setJieswjm(fileName);
//                    agKuawcsJs.setBaoclj(fileFullPath);
//                    agKuawcsJs.setDuqsj(new Date());
//                    agKuawcsJs.setJieswcsj(new Date());
//                    agKuawcsJsService.save(agKuawcsJs);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

//        }



    }

    //读文件，返回字符串
    public String ReadFile(String path){
        File file = new File(path);
        BufferedReader reader = null;
        String laststr = "";
        try {
            //System.out.println("以行为单位读取文件内容，一次读一整行：");
           // reader = new BufferedReader(new FileReader(file));
            reader =   new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
            String tempString = null;

            //一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                //显示行号
                laststr = laststr +tempString;

            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return laststr;
    }

    /**
     * 关闭流
     */
    private void close(InputStream in,FileOutputStream fos,String ret) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            if(in != null){
                in.close();
            }
            if(fos != null){
                fos.close();
            }
        } catch (IOException e) {
            ret = ret+"  "+"接收失败！";

            log.error("接收失败",e);
        }
    }

    /**
     * 返回响应
     */
    private void sendResponse(String responseString,HttpServletResponse response,String ret){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write(responseString);
            pw.flush();
        } catch (IOException e) {
            ret = ret+"  "+"响应消息发送失败！";

            log.error("响应消息发送失败",e);
        }finally {
            IOUtils.closeQuietly(pw);
        }
    }



    /*
    光盘接收
     */
    @Override
    public Result <?> receive(HttpServletRequest request, HttpServletResponse response) {
        log.info("跨网传输光盘接收开始"+DateUtils.formatDateTime());
        //request参数传的目录
        String path=request.getParameter("ftpFilePath");
        log.info(request.getParameter("ftpFilePath"));


        AgKuawcsJs agKuawcsJs = new AgKuawcsJs();
        agKuawcsJs.setJieskssj(new Date());
        int num;
        if (path.contains("anguan_guangpan")){
            agKuawcsJs.setJieswjm(path.substring(path.indexOf("anguan_guangpan")));
            num=path.indexOf("anguan_guangpan")-1;
        }else{
            agKuawcsJs.setJieswjm(path.substring(path.indexOf("anguan_guangpan")));
            num=path.indexOf("Rx")-1;
        }


        FtpUtil ftp = new FtpUtil(username,password, guangpnwIp,port);


        try {
            //下载


            String ftpFilePath="/home/admin"+path.substring(0,num);
            ftp.down(ftpFilePath,savePath);


            agKuawcsJs.setChuansfs("1");
            agKuawcsJs.setJieswcsj(new Date());
            agKuawcsJs.setJieswjm(path);
            agKuawcsJs.setBaoclj(savePath);
            agKuawcsJs.setDuqsj(new Date());
            agKuawcsJsService.save(agKuawcsJs);


        } catch (IOException e) {
            e.printStackTrace();
            Result.error("接收文件失败！");

        }

        return Result.ok("接收文件成功!");

    }


}
